/**
 * @description: 添加 debug 模式
 * @update: 2019-07-26
 * @version: 2.2
 **/

/* == plat ==
* 支持：changyou(畅游) phone(手机) warframe(星际战甲) wechat(微信)   cyou3(橙柚三联)
* 不支持：changyoujia(畅游加) Anonymous(匿名访问) DJ(刀剑)
*/
'use strict';

(function () {
    var that;
    var name = 'ja';
    var version = '2.2';
    var JoinActivity = function () {
        // -----------------全局变量----------------
        this.jsvs = undefined;
        this.options = {
            app: undefined,             // 应用 初始化必传项
            activity: undefined,        // 活动 初始化必传项
            version: undefined,         // 版本 初始化必传项
            platform: undefined,        // 平台 初始化必传项

            isUserInit: false,          // 是否获取用户信息
            isWxLogin: false,           // 是否微信授权
            isWxInit: false,            // 是否微信初始化，开启后才能使用微信功能
            isWxDebug: false,           // 是否开启微信debug调试
            isDebug: false,             // 是否开启调试模式
            debugPath: '/app/json',     // debug 请求基础路径
            host: location.origin,      // 接口请求域名，默认同域名
            appId: undefined,           // 微信 appId 手动添加，权重大于 init 接口的 wxId
            wxShare: undefined,         // 微信分享内容
            ele: {
                inputPhone: '.input_phone',
                inputPhoneCode: '.input_phone_code',
                btnPhone: '.btn_phone',
                btnPhoneCode: '.btn_phone_code'
            },
            ready: function() {},   // 回调函数
    };
        this.glob = {
            isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),
            isWechat: window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger',
            arrEnable: ['app', 'activity', 'version', 'platform'],
            code: 0,                    // 初始化状态：0 初始化未完成;1 初始化成功;2 活动未开始;3 活动已结束;4 用户未登录; 5 活动无效
            appName: undefined,         // 活动唯一标识
            cyscid: undefined,          // 来源标识
            cystid: undefined,          // 来源标识
            token: undefined,           // token
            userInfo: undefined,        // 用户信息
            wechatInfo: undefined,      // 微信用户信息
            activityInfo: undefined,    // 活动信息
            wxBindInfo: undefined       // 微信绑定信息
        };
        that = this;
    };
    JoinActivity.fn = JoinActivity.prototype = {
        // -----------------初始化----------------
        config: function(options) {
            $.extend(this.options, options);
            if(this.admin.enable()) {
                this.admin.set();
                that.user.getToken(function(res) {
                    if(res.code === 10000) {
                        if((that.options.platform !== 'wechat' && that.glob.isWechat && that.options.isWxLogin) || that.options.platform === 'wechat') {
                            that.user.getUserInfo('wechat', function() {
                                that.admin.manage();
                            });
                        }else {
                            that.admin.manage();
                        }
                    }else {
                        that.options.ready(that.glob);
                    }
                })
            }
        },
        // -----------权限(辅助config参数判断)----------------
        admin: {
            enable: function() {
                var isPass = true
                    , arrMust = that.glob.arrEnable;
                // 必填项
                arrMust.forEach(function (item, index) {
                    if(!that.options[item]) {
                        alert(item + '为必填项');
                        arrMust = arrMust.concat(arrMust.splice(index, arrMust.length - index));
                        isPass = false;
                    }
                });
                if(that.options.platform === 'wechat' && !that.glob.isWechat) {
                    alert('请在微信中访问');
                    isPass = false;
                }
                return isPass;
            },
            set: function() {
                that.glob.appName = that.options.app + '-' + that.options.activity + '-' + that.options.version + '-' + that.options.platform;
                var cyscid = that.utils.getQueryString('CYSCID');
                var cystid = that.utils.getQueryString('CYSTID');
                if(cyscid) that.admin.store.set('cyscid', cyscid);
                if(cystid) that.admin.store.set( 'cystid', cystid);
                that.glob.cyscid = that.admin.store.get('cyscid') || undefined;
                that.glob.cystid = that.admin.store.get('cystid') || undefined;
            },
            manage: function() {
                if(that.glob.isWechat) {
                    if(that.options.isWxInit) {
                        that.wx.init(function() {
                            if(that.options.wxShare) that.wx.share(that.options.wxShare);
                        })
                    }
                }
                if(that.options.isUserInit) {
                    that.user.getUserInfo(that.options.platform, that.options.ready)
                }else {
                    that.options.ready(that.glob);
                }
            },
            error: function(msg) {
                throw new Error(name + version + ': ' + msg);
            },
            store: {
                set: function(key, val) {
                    that.utils.session.set(that.glob.appName + ':' + key, val);
                },
                get: function(key) {
                    return that.utils.session.get(that.glob.appName + ':' + key);
                }
            }
        },
        // ----------------- 全局使用 ----------------
        common: {
            // 移动端初始化
            mobile: function() {
                $('input').blur(function() { window.scrollTo(0, 0) });  // 解决 H5 在输入弹框后页面留白问题
            },
            // 输出最新全局对象 glob
            glob: function() {
                return that.glob;
            },
            // 百度事件统计
            baiduEvent: function(actName, sign, action, isPcM, isTwo) {
                if(window._hmt) {
                    var cid = that.glob.cyscid
                        , tid = that.glob.cystid
                        , remark = isTwo ? ((cid ? ('cid=' + cid) : '无cid') + '/' + (tid ? ('tid=' + tid) : '无tid')) : (that.glob.cyscid || '无');
                    if(isPcM) remark += ('/' + (that.glob.isMobile ? 'm' : 'pc'));
                    window._hmt.push(['_trackEvent', actName + sign, action + sign, remark + '/' +sign]);
                }else {
                    that.admin.error('请先添加百度统计代码');
                }
            }
        },
        // -----------------表单验证----------------
        verify: {
            reg: {
                phone: /^1[3456789]\d{9}$/,
                email: /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/,           // 邮箱
                userName: /^[a-z0-9_-]{3,16}$/,                     // 用户名
                chineseName: /^[\u4E00-\u9FA5]{2,4}$/,              // 中文姓名
            },
            // 手机号
            phone: function (val) {
                if (!val) {
                    return '请填写手机号！';
                } else if (!val.match(this.reg.phone)) {
                    return '请输入正确的手机号！';
                } else {
                    return false;
                }
            },
            // 验证码
            code: function (val) {
                if (!val) {
                    return '请填写验证码！';
                } else if (val.length !== 6) {
                    return '验证码错误！'
                } else {
                    return false;
                }
            }
        },
        // ----------------- 工具类 ----------------
        utils: {
            getQueryString: function(name) {
                var reg = new RegExp('(^|&)'+ name +'=([^&]*)(&|$)');
                var r = window.location.search.substr(1).match(reg);
                if(r!=null)return  unescape(r[2]); return null;
            },
            isJSON: function(str) {
                if (typeof str == 'string') {
                    try {
                        var obj = JSON.parse(str);
                        if(typeof obj == 'object' && obj ){
                            return true;
                        }else{
                            return false;
                        }
                    } catch(e) {
                        return false;
                    }
                }
            },
            isObject: function(o) {
                return (typeof o === 'object' || typeof o === 'function') && o !== null
            },
            objDelUndefined: function(obj) {
                var json = {};
                for(var key in obj) {
                    if(obj[key]) json[key] = obj[key];
                }
                return json;
            },
            backTop: function(num) {
                $('html, body').animate({scrollTop: num + 'px'}, 300);
            },
            objType: function(val) {
               var json = {
                   '[object Object]': 'object',
                   '[object Array]': 'array',
                   '[object Number]': 'number',
                   '[object Function]': 'function',
                   '[object Null]': 'null',
                   '[object Undefined]': 'undefined',
                   '[object Boolean]': 'boolean',
                   "[object String]" : 'string'
               };
               return json[Object.prototype.toString.call(val)]
            },
            // 弹窗
            win: {
                scrolling: 'no',
                //是否显示滚动条 no,yes,auto
                int: function () {
                    $("#winClose").on('mouseenter',
                        function () {
                            $(this).css("background-image", "url()");
                        });
                    $("#winClose").on('mouseleave',
                        function () {
                            $(this).css("background-image", "url()");
                        });
                    $("#winClose").on('click',
                        function () {
                            $("#mask,#maskTop").fadeOut(function () {
                                $(this).remove();
                            });
                        });
                },
                open: function (width, height, src) {
                    var iframeHeight = height;
                    var marginLeft = width / 2;
                    var marginTop = height / 2;
                    var inntHtml = '';
                    inntHtml += '<div id="mask" style="width:100%; height:100%; position:fixed; top:0; left:0; z-inde:1999;background:#cccccc; filter:alpha(opacity=50); -moz-opacity:0.5; -khtml-opacity: 0.5; opacity:0.5;"></div>';
                    inntHtml += '<div id="maskTop" style="width: ' + width + 'px; height: ' + height + 'px;  color: #333; position: fixed; top: 50%; left: 50%; margin-left: -' + marginLeft + 'px; margin-top: -' + marginTop + 'px; z-index: 2999; ">';
                    inntHtml += '<div id="maskTitle" style="height: 0;position: relative;">';
                    inntHtml += '<div id="winClose" style="width: 28px; height: 28px; cursor: pointer; position: absolute; top: -12px; right: -9px; background-image: url();"></div>';
                    inntHtml += '</div>';
                    inntHtml += '<iframe width="' + width + '" height="' + iframeHeight + '" frameborder="0" scrolling="' + this.scrolling + '" src="' + src + '"></iframe>';
                    inntHtml += '</div>';
                    $("body").append(inntHtml);
                    this.int();
                },
                close: function () {
                    $("#winClose").click();
                }
            },
            // 本地存储
            cookie: {
                get: function(cname) {
                    var name = cname + '=';
                    var ca = document.cookie.split(';');
                    for(var i=0; i<ca.length; i++) {
                        var c = ca[i];
                        while (c.charAt(0)==' ') c = c.substring(1);
                        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
                    }
                    return '';
                },
                set: function(cname, cvalue, exdays, domain) {
                    var d = new Date();
                    d.setTime(d.getTime() + (exdays*24*60*60*1000));
                    var expires = 'expires='+d.toUTCString();
                    document.cookie = cname + '=' + cvalue + '; ' + expires + '; domain=' + domain + '; path=/';
                },
                del: function(name, domain) {
                    this.set(name, '', -1, domain);
                }
            },
            session: {
                set: function(name, value) {
                    if(Object.prototype.toString.call(value) === '[object object]') value = JSON.stringify(value);
                    sessionStorage.setItem(name, value)
                },
                get: function(name) {
                    var value = sessionStorage.getItem(name);
                    return that.utils.isJSON(value) ? JSON.parse(value) : value;
                },
                remove: function(name) {
                    sessionStorage.removeItem(name);
                },
                clear: function() {
                    sessionStorage.clear();
                }
            }
        },
        // -----------------ajax请求----------------
        client: {
            ajax: function (type, url, variate, fun) {
                switch (that.utils.objType(variate)) {
                    case 'object': var data = variate; break;
                    case 'function': fun = variate; break;
                    default: that.admin.error('client.ajax使用错误');
                }
                $.ajax({
                    type: type,
                    url: url + (that.options.isDebug ? '.json' : ''),
                    data: data || {},
                    dataType: 'json',
                    cache: false,
                    xhrFields: { withCredentials: true },
                    headers: that.utils.objDelUndefined({
                        'Authorization': that.glob.token,
                        'APP': that.options.app,
                        'ACTIVITY': that.options.activity,
                        'VERSIONCODE': that.options.version,
                        'CYSCID': that.glob.cyscid,
                        'CYSTID': that.glob.cystid,
                        "JSVS": that.jsvs
                    }),
                    success: function(res) {
                        fun(res)
                    }
                })
            },
            common: function(type, url, variate, fun, plat) {
                switch (that.utils.objType(variate)) {
                    case 'string': plat = variate; break;
                    case 'object': var data = variate; break;
                    case 'function': fun = variate; break;
                    default: that.admin.error('接口' + url +  '请求方法使用错误, 第二个参数请传入有效参数');
                }
                var baseUrl = that.options.host + (that.options.isDebug ? that.options.debugPath : '/' + (plat || that.options.platform));
                this.ajax(that.options.isDebug ? 'GET': type, baseUrl + url, data || {}, fun);
            },
            get: function(url, variate, fun, plat) {
                this.common('GET',  url, variate, fun, plat);
            },
            post: function(url, variate, fun, plat) {
                this.common('POST', url, variate, fun, plat);
            }
        },
        // -----------------用户业务----------------
        user: {
            url: {
                name: function() { return that.options.app + '-' + that.options.activity + '-' + that.options.version },
                core: function() {
                    if(that.options.isDebug) {
                        return '/' + that.options.platform;
                    }else {
                        return  '/core/login/' + that.options.app + '/' + that.options.activity + '/' + that.options.version
                    }
                },
                tokenPath: '/landing/init',
                userInfoPath: '/user/info'          // 用户详情
            },
            // 获取token
            getToken: function(fun) {
                that.client.get(this.url.tokenPath, function (res) {
                    switch (res.code) {
                        case 10000:             // 初始化正常
                            !that.options.isUserInit && (that.glob.code = 1);
                            that.glob.activityInfo = res.data.activity;
                            that.glob.token = res.data.token;
                            if(!that.options.appId) that.options.appId = res.data.activity.wxId;
                            break;
                        case 1106:             // 活动未开始
                            that.glob.code = 2;
                            break;
                        case 1103:             // 活动已结束
                            that.glob.code = 3;
                            break;
                        case 1102:             // 活动无效
                            that.glob.code = 5;
                            alert(res.message);
                            break;
                        default:                // 其他
                            that.glob.code = 99;
                            alert(res.message);
                            break;
                    }
                    fun && fun(res);
                });
            },
            // 获取验证码
            getCode: function(obj, num) {        // obj 值可以是回调函数，可以是点击获取按钮后样式
                var name = 'phone_code_num'
                    , codeInit = 60
                    , phone = num || $(that.options.ele.inputPhone).val()
                    , errorPhone = that.verify.phone(phone);
                if(errorPhone) {
                    alert(errorPhone);
                    return false;
                }
                $(that.options.ele.btnPhoneCode).html('发送中...').css('pointer-events','none');
                that.client.post('/core/zhpt/sendcode', { phone: phone }, function(res) {
                    if(obj && that.utils.objType(obj) === 'function') {
                        obj(res)
                    }else {
                        if(res.code === 10000) {
                            var codeNum = codeInit;
                            var timer = setInterval(function() {
                                that.utils.session.set(name, codeNum);
                                var style = obj && that.utils.objType(obj) === 'object' ? obj : {background: '#9c9c9c'};
                                $(that.options.ele.btnPhoneCode).text(codeNum + 's').css(style);
                                if(codeNum <= 0) {
                                    $(that.options.ele.btnPhoneCode).text('获取验证码').css({background: ''}).css('pointer-events','auto');
                                    that.utils.session.remove(name);
                                    clearInterval(timer);
                                }
                                codeNum --;
                            }, 1000)
                        }else {
                            alert(res.message);
                            $(that.options.ele.btnPhoneCode).text('获取验证码').css({background: ''}).attr('pointer-events','auto');
                            that.utils.session.remove(name);
                        }
                    }
                }, 'phone');
            },
            // 手机号与验证码登陆
            loginPhone: function(phone, code, fun) {
                var errorPhone = that.verify.phone(phone)
                    , errorPhoneCode = that.verify.code(code);
                if(errorPhone) {
                    alert(errorPhone);
                    return false;
                }
                if(errorPhoneCode) {
                    alert(errorPhoneCode);
                    return false;
                }
                that.client.post(this.url.core() + '/phonelogin', {
                    phone: phone,
                    code: code
                }, function(res) {
                    fun ? fun(res) : res.code === 10000 ? location.reload() : alert(res.message);
                }, 'phone');
            },
            // 获取用户信息
            getUserInfo: function(variate, fun) {
                if(that.utils.objType(variate) === 'function') {
                    fun = variate;
                }else {
                    var plat = variate;
                }
                that.client.get(this.url.userInfoPath, plat, function(res) {
                    if(plat === 'wechat') {
                        if(res.code === 10000) {
                            that.glob.wechatInfo = res.data;
                        }else {
                            that.user.login('wechat');
                        }
                    }else {
                        if(res.code === 10000) {
                            that.glob.userInfo = res.data;
                            that.glob.code = 1;
                        }else {
                            that.glob.code = 4;
                        }
                    }
                    fun && fun(that.glob);
                })
            },
            // 登陆弹窗
            login: function(platform, back) {
                var plat = platform || that.options.platform
                    , url = that.options.host + '/' + plat + this.url.core() + '?callback=' + encodeURI(back || location.href)
                    , isMobile = that.glob.isMobile
                    , isWechat = that.glob.isWechat;
                switch (plat) {
                    case 'warframe':
                        isMobile ? window.location.href = url : that.utils.win.open(490, 352, url);
                        break;
                    case 'changyou':
                        isMobile ? window.location.href = url : that.utils.win.open(490, 352, url);
                        break;
                    case 'cyou3':
                        isMobile ? window.location.href = url : that.utils.win.open(490, 470, url);
                        break;
                    case 'wechat':
                        isWechat && (window.location.href = url);
                        break;
                    default:
                        alert('暂时还没有该平台登陆功能');
                }
            },
            // 是否绑定微信
            wxIsBind: function(fun) {
                that.client.post('/auto/isbind', 'wechat', function(res) {
                    fun && fun(res);
                })
            },
            wxAutoLogin: function(fun) {
                that.client.post('/auto/autologin', 'wechat', function(res) {
                    fun && fun(res);
                })
            },
            // 登出
            logout: function (fun) {
                if(that.glob.isWechat && that.options.isWxLogin && that.options.isUserInit) {
                    this.logoutWx()
                }else {
                    this.logoutAct(fun);
                }
            },
            logoutWx: function() {
                that.client.post('/auto/cancel', 'wechat', function(res) {
                    if(res.code === 10000) {
                        that.user.logoutAct();
                    }
                })
            },
            logoutAct: function(fun) {
                that.client.post(this.url.core() + '/logout', function () {
                    if(['changyou', 'warframe', 'wechat'].indexOf(that.options.platform) !== -1) {
                        that.utils.cookie.del('CASGTC', '.changyou.com');
                        location.href = 'https://auth.changyou.com/logout.jsp?b=' + location.href.split("#")[0] + '&co=' + that.utils.cookie.get("CASGTC");
                    }
                    that.utils.session.clear();
                    fun || location.reload();
                });
            }
        },
        // -----------------微信业务----------------
        wx: {
            // 微信初始化
            init: function(fun) {
                if(!that.options.appId) {
                    return that.admin.error('微信初始化失败，没有得到 wxId');
                }
                if(typeof wx === 'undefined') {
                    return that.admin.error('微信初始化失败，请引入 https://res.wx.qq.com/open/js/jweixin-1.4.0.js');
                }
                $.ajax({
                    url: location.origin + '/wechat/web/' + that.options.appId + '/config?_=' + Date.now(),
                    success: function(data) {
                        if(data.config) {
                            wx.config({
                                debug: that.glob.isWxDebug ,        // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                                appId: data.config.appId,           // 必填，公众号的唯一标识
                                timestamp: data.config.timestamp,   // 必填，生成签名的时间戳
                                nonceStr: data.config.nonceStr,     // 必填，生成签名的随机串
                                signature: data.config.signature,   // 必填，签名，见附录1
                                jsApiList: [                        // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                                    'translateVoice',
                                    'onMenuShareTimeline',
                                    'onMenuShareAppMessage',
                                    'onMenuShareQQ',
                                    'onMenuShareWeibo',
                                    'hideMenuItems',
                                    'hideAllNonBaseMenuItem',
                                    'onMenuShareQZone'
                                ]
                            });
                            fun && fun();
                        }else {
                            that.admin.error('微信初始化失败，' + data.msg);
                        }
                    }
                });
            },
            // 分享
            share: function(options) {
                var _options = {
                    type: 'link',
                    shareList: [
                        'onMenuShareTimeline',      // 分享到朋友圈
                        'onMenuShareAppMessage',    // 分享给朋友
                        'onMenuShareQQ',            // 分享到QQ
                        'onMenuShareWeibo',         // 分享到腾讯微博
                        'onMenuShareQZone'          // 分型到QQ空间
                    ]
                };
                _options = $.extend(_options, options);
                var list = _options.shareList;
                delete _options['shareList'];
                wx.ready(function() {
                    for(var i in list) {
                        var shareType = list[i];
                        if($.isFunction(wx[shareType])) {
                            wx[shareType](_options);
                        }
                    }
                })
            }
        }
    };
    window[name] = new JoinActivity();
}());